package me.firstapp.bbs.controller.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import me.firstapp.common.module.bbs.JsonMember;
import me.firstapp.common.utils.CookieUtils;
import me.firstapp.common.utils.SpringContextTool;
import me.firstapp.common.utils.StrUtils;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		boolean isLogined = false;
		Cookie cookie = CookieUtils.getCookieByName(request, "loginToken");
		if (cookie == null) {
			isLogined = false;
		} else {
			String loginToken = CookieUtils.getCookieByName(request, "loginToken").getValue();
			if (StrUtils.isNULL(loginToken)) {
				isLogined = false;
			} else {
				ApplicationContext applicationContext = SpringContextTool.getApplicationContext();
				@SuppressWarnings("unchecked")
				RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) applicationContext
						.getBean("redisTemplate");

				JsonMember member = (JsonMember) redisTemplate.opsForValue().get("login_member_" + loginToken);
				if (member == null) {
					isLogined = false;
				} else {
					isLogined = true;
				}
			}
		}

		if (isLogined) {
			return true;
		} else {
			request.getRequestDispatcher("/member/login").forward(request, response);
			return false;
		}
	}

}
